package com.dayuanit.dy17.mix.thread;

public class TestThreadWaitNotifyAll {

    public static int flag = 1;
    public static final int totalThread = 5;

    public static final Object lock = new Object();

    public static class MyRunnable implements Runnable {
        private int myFlag;

        public MyRunnable(int myFlag) {
            this.myFlag = myFlag;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    print();
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        private void print() throws Exception {
            synchronized (lock) {
                while (myFlag != flag) {
                    lock.wait();
                }

                System.out.println("run() " + Thread.currentThread().getName());

                if (flag == totalThread) {
                    flag = 1;
                } else {
                    flag ++;
                }

                lock.notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new MyRunnable(1), "t1").start();
        new Thread(new MyRunnable(2),"t2").start();
        new Thread(new MyRunnable(3),"t3").start();
        new Thread(new MyRunnable(4),"t4").start();
        new Thread(new MyRunnable(5),"t5").start();
    }
}
